import React, { Component, PropTypes } from 'react';
import CompactInput from 'components/compact-input'
import { Form, Select, Input } from 'antd';
import Chooser from 'components/chooser'
import Searcher from 'components/searcher'
import { messages, deepFullCopy } from "share/common";
const FormItem = Form.Item;
const Option = Select.Option;
import formService from 'containers/setting/form/form.service'
import baseService from 'share/base.service'
import chooserData from 'share/chooserData'

class AllocationExpense extends Component {

  range = [{
    value: 'RELATED',
    text: messages('request-2.key1')/*同关联申请单费用*/
  }, {
    value: 'ALL',
    text: messages('request-2.key2')/*全部费用*/
  }, {
    value: 'PARTIAL',
    text: messages('request-2.key3')/*部分费用*/
  }];

  state = {
    range: 'ALL',
    value: [],
    fatherExpenseType: [], //所属父类型，用于分配费用中下拉框的数据，不能直接在弹框里渲染，因为chrome和opera会有Background Tabs Throttling
    expenseTypeCategory: [], //费用大类，不直接在弹框中渲染，理由同上
  };

  componentMap = {
    Chooser,
    Searcher
  };

  handleChangeRange = range => {
    this.setState({ range, value: [] }, this.dispatchOnChange)
  };

  componentDidMount() {
    const { value, setOfBooksId } = this.props;
    this.setValue(this.props.value);
    this.initFatherExpenseType(setOfBooksId);
    this.initExpenseTypeCategory(setOfBooksId);
  }

  componentWillReceiveProps(nextProps) {
    if('value' in nextProps) {
      this.setValue(nextProps.value)
    }
    if (nextProps.setOfBooksId !== this.props.setOfBooksId) {
      this.initFatherExpenseType(nextProps.setOfBooksId);
      this.initExpenseTypeCategory(nextProps.setOfBooksId);
    }
  }

  //获取所属父类型
  initFatherExpenseType = (setOfBooksId) => {
    let fatherExpenseType = [];
    formService.getFatherExpenseType(setOfBooksId, 'ALL').then(res => {
      if (res.data && res.data.length) {
        res.data.map(expense => {
          fatherExpenseType.push({label: expense.name, value: expense.id});
        });
        this.setState({fatherExpenseType});
      }
    }).catch(error => {
      console.log(error);
    });
  };

  //获取所有费用大类
  initExpenseTypeCategory = (setOfBooksId) => {
    let expenseTypeCategory = [];
    baseService.getExpenseTypeCategory(setOfBooksId, 'ALL').then(res => {
      if (res.data && res.data.length) {
        res.data.map(category => {
          expenseTypeCategory.push({label: category.name, value: category.id});
        });
        this.setState({expenseTypeCategory});
      }
    }).catch(error => {
      console.log(error);
    });
  };

  setValue = value => {
    if(value) {
      const { parser } = this.props;
      this.setState(parser(value));
    }
  };

  renderValueComponent = () => {
    const { range, value, fatherExpenseType, expenseTypeCategory } = this.state;
    const { componentProps, component, setOfBooksId, disabled } = this.props;
    switch(range) {
      case 'RELATED':
      case 'ALL':
        return <Input disabled value={messages('request-2.key4')/*通用*/}/>;
      case 'PARTIAL':
        let chooserItem = deepFullCopy(chooserData['available_expense']);
        let selectItem = {
          type: 'select',
          id: 'parentId',
          label: messages('request-2.key5')/*所属父类型*/,
          options: fatherExpenseType
        };
        let selectItem2 = {
          type: 'select',
          id: 'expenseTypeCategoryId',
          label: messages('request-2.key6')/*费用大类*/,
          options: expenseTypeCategory
        };
        chooserItem.searchForm.push(selectItem);
        chooserItem.searchForm.push(selectItem2);
        const partialExpenseProps = Object.assign({}, {
          labelKey: 'name',
          valueKey: 'expenseTypeOID',
          showNumber: true,
          selectorItem: chooserItem,
          listExtraParams: {
            setOfBooksId: setOfBooksId || undefined,
            enabled: true,
            levelCode: 'ALL'
          }
        }, componentProps[range]);
        const PartialExpenseComp = this.componentMap[component[range]] || 'Chooser';
        return <PartialExpenseComp
          value={value}
          disabled={disabled}
          onChange={this.onChangeValue}
          {...partialExpenseProps}
        />;
    }
  };

  onChangeValue = value => {
    this.setState({ value }, this.dispatchOnChange);
  };

  dispatchOnChange = () => {
    const { range, value } = this.state;
    const { onChange, formatter } = this.props;
    onChange && onChange(formatter({
      range, value
    }))
  };

  render() {
    const { hidden, disabled, value } = this.props;
    return (
      <div>
        <CompactInput>
          <Select
            disabled={disabled}
            style={{width: '100%'}}
            onChange={this.handleChangeRange}
            value={value && value.range}
            getPopupContainer={triggerNode => triggerNode.parentNode}
          >
            {
              this.range
                .filter(item => hidden.indexOf(item.value) === -1)
                .map(option => <Option key={option.value}>{option.text}</Option>)
            }
          </Select>
          {this.renderValueComponent()}
        </CompactInput>
      </div>
    );
  }

  static propTypes = {
    onChange: PropTypes.func,
    hidden: PropTypes.array,
    component: PropTypes.object,
    componentProps: PropTypes.object,
    parser: PropTypes.func,
    formatter: PropTypes.func,
    disabled: PropTypes.bool
  };

  static defaultProps = {
    onChange: () => {},
    hidden: [],
    component: {
      'PARTIAL': 'Chooser'
    },
    componentProps: {
      'PARTIAL': {}
    },
    parser: value => value,
    formatter: value => value,
    disabled: false
  };
}

export default AllocationExpense;
